# -*- encoding: utf-8 -*-
import xmltodict
import thread
from types import *
from datetime import datetime
from peliculas.models import Movie, Genre, Director, Actor, PurchaseOption, Score
from django.shortcuts import render
from django import http, forms
import xml.etree.ElementTree as ET


# Create your views here.

class SimpleFileForm(forms.Form):
	file = forms.Field(widget=forms.FileInput, required=False)

# Ver película específica
def movie(request, idMovie):

	movie = Movie.objects.get(id = idMovie)
	genres = Genre.objects.all().order_by('genreName')

	# Extraer peliculas recomendadas
	recommend_movies = Movie.objects.filter( classificationAdult = False, genre = movie.genre.all()).order_by('?')[:8]

	context = {'movie':movie, 'genres':genres, 'recommend_movies':recommend_movies}
	return render(request, 'monster/movie.html', context)

# Ver todas las películas de un género específico
def genreMovies(request, idGenre):

	genre1 = Genre.objects.filter( id = idGenre)
	movies = Movie.objects.filter(classificationAdult = False, genre = genre1).order_by('title')[:16]
	genres = Genre.objects.all().order_by('genreName')

	context = {'movies':movies, 'genres':genres}
	return render(request, 'monster/movies.html', context)

# Ver todas las películas
def movies(request):

	movies = Movie.objects.filter(classificationAdult = False).order_by('title')[:16]
	genres = Genre.objects.all().order_by('genreName')

	context = {'movies':movies, 'genres':genres}
	return render(request, 'monster/movies.html', context)

def monster(request):
	
	carrusel = Movie.objects.filter(year = 2014, classificationAdult = False)[:6]
	movies = Movie.objects.filter(classificationAdult = False).order_by('?')[:8]


	action_genre = Genre.objects.filter(genreName = 'Acción')
	comedy_genre = Genre.objects.filter(genreName = 'Comedia')
	
	action_movies = Movie.objects.filter(genre = action_genre, classificationAdult = False).order_by('?')[:4]
	comedy_movies = Movie.objects.filter(genre = comedy_genre, classificationAdult = False).order_by('?')[:4]


	genres = Genre.objects.all().order_by('genreName')

	context = {'movies':movies, 'carrusel':carrusel, 'genres':genres, 'action_movies':action_movies, 'comedy_movies':comedy_movies}
	return render(request, 'monster/index.html', context)

def login(request):

	context = {}
	return render(request, 'monster/login.html', context)

def index(request):
	if request.method == 'POST':
		if 'file' in request.FILES:
			file = request.FILES['file']
			filecontent = file.read()
			root = ET.fromstring(filecontent)
			for child in root:
				if child.tag == 'Movie':
					correct = True
					m = Movie()
					try:
						m.id_XML = child.find('Id').text
					except AttributeError:
						correct = False
					try:
						mm = Movie.objects.get(id_XML = m.id_XML)
					except Movie.DoesNotExist:
						try:
							m.title = child.find('Title').text
						except AttributeError:
							correct = False
						try:
							m.plot = child.find('Plot').text
						except AttributeError:
							correct = False
						try:
							m.publicWebUri = child.find('PublicWebUri').text
						except AttributeError:
							correct = False
						try:
							modifiedDate = child.find('LastModifiedDate').text
							m.lastModifiedDate = datetime.strptime(modifiedDate[:21], '%Y-%m-%dT%I:%M:%S.%f')
						except (AttributeError, KeyError, TypeError, ValueError):
							m.lastModifiedDate = datetime.now()
						try:
							originalPublicationDate = child.find('OriginalPublicationDate').text
							m.originalPublicationDate = datetime.strptime(modifiedDate[:21], '%Y-%m-%dT%I:%M:%S.%f')
						except (AttributeError, KeyError, TypeError, ValueError):
							m.originalPublicationDate = datetime.now()
						try:
							m.artwork = child.find('Artwork').text
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.classificationName = child.find('Classification').find('Name').text
							if child.find('Classification').find('Adult').text == 'false':
								m.classificationAdult = False
							else:
								m.classificationAdult = True
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.year = child.find('Year').text
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.duration = child.find('Duration').text
						except (AttributeError, KeyError, TypeError):
							m.duration = '-'
						m.save()
						try:
							for gname in child.find('Genres'):
								genre = gname.text
								try:
									g = Genre.objects.get(genreName = genre)
								except Genre.DoesNotExist:
									g = Genre()
									g.genreName = genre
									g.save()
								m.genre.add(g)
						except (AttributeError, KeyError, TypeError):
							pass
						try:
							for dname in child.find('Directors'):
								director = dname.find('Name').text
								try:
									d = Director.objects.get(directorName = director)
								except Director.DoesNotExist:
									d = Director()
									d.directorName = director
									d.save()
								m.director.add(d)
						except (AttributeError, KeyError, TypeError):
							pass
						try:
							for aname in child.find('Actors'):
								actor = aname.find('Name').text
								try:
									a = Actor.objects.get(actorName = actor)
								except Actor.DoesNotExist:
									a = Actor()
									a.actorName = actor
									a.save()
								m.actor.add(a)
						except (KeyError, TypeError):
							pass
						try:
							for p in child.find('PurchaseOptions'):
								po = PurchaseOption()
								po.offerType =  p.find('OfferType').text
								po.price =  p.find('Price').text
								po.currency =  p.find('Currency').text
								po.videoQuality =  p.find('VideoQuality').text
								po.movie = m
								po.save()
						except (KeyError, TypeError):
							pass
						try:
							for p in child.find('Scores'):
								sco = Score()
								sco.scoreValue = p.find('Value').text
								sco.scoreUrl = p.find('Url').text
								sco.movie = m
								sco.save()
						except (KeyError, TypeError):
							pass


			
				
			context = {'upload':True}
			return render(request, 'index.html', context)
	else:
		# display the form
		form = SimpleFileForm()
		context = {'upload':False, 'form':form}
		return render(request, 'index.html', context)